const query = require("../config/db")
var express = require("express")
var router  = express.Router()

router.get("/search",async(req,res,next)=>{
    let {keys='',page=1,size=10} = req.query
    page = Number(page)
    size = Number(size)

    // 判断关键词不能为空
    if(keys === ''){
        next("请输入关键词")
        return
    }

    // 假如有关键词
    let sql1 = `select * from e_course where title like '%${keys}%' OR area_name LIKE '%${keys}%' OR grade_name LIKE '%${keys}%' OR subject_name LIKE '%${keys}%' or category_name LIKE '%${keys}%'`;
    let result1 = await query(sql1)

    let totalNum = result1.length
    let totalPage= Math.ceil(totalNum/size)

    let sql2 = `select * from e_course where title like '%${keys}%' OR area_name LIKE '%${keys}%' OR grade_name LIKE '%${keys}%' OR subject_name LIKE '%${keys}%' or category_name LIKE '%${keys}%' limit ${(page-1) * size},${size}`
    let result2 = await query(sql2)
    res.send({
        success:true,
        msg:"查询成功",
        status:200,
        data:{
            totalNum,
            totalPage,
            page,
            list:result2
        }
    })
})

module.exports = router